package com.kning.poiword.replace;

import com.kning.poiword.model.Chart;
import com.kning.poiword.model.Picture;
import com.kning.poiword.model.Table;
import com.kning.poiword.model.Text;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version : 1.0
 * @author : 王康宁
 * @date : 2020/1/7
 **/
public class ReplaceDocumentImpl implements ReplaceDocument {

    private static ReplaceDocComponent replaceDocComponent = new ReplaceDocComponentImpl();

    @Override
    public void replaceAllComponent(XWPFDocument document,
                                    List<Text> text,
                                    List<Picture> picture,
                                    List<Table> table,
                                    List<Chart> chart) {

        //替换文字和图片
        if (!CollectionUtils.isEmpty(text)) {
            replaceDocComponent.replaceText(text, document);
        }

        //解析document
        Map<String, POIXMLDocumentPart> documentChartMap = analyseDocumentChart(document);

        //匹配构建chart
        if (!CollectionUtils.isEmpty(documentChartMap) && !CollectionUtils.isEmpty(chart)) {
            chart.forEach(t -> {
                POIXMLDocumentPart poixmlDocumentPart = documentChartMap.get(t.getChartNumber());
                replaceDocComponent.replaceChart(t, poixmlDocumentPart);
            });
        }

        //动态刷新
    }

    protected Map<String, POIXMLDocumentPart> analyseDocumentChart(XWPFDocument document) {
        //模板图表元素解析
        Map<String, POIXMLDocumentPart> chartsMap = new HashMap<String, POIXMLDocumentPart>();
        //动态刷新图表
        List<POIXMLDocumentPart> relations = document.getRelations();
        relations.forEach(t -> {
            if (t instanceof XWPFChart) {
                String str = t.toString();
                System.out.println("str：" + str);
                String key = str.replaceAll("Name: ", "")
                        .replaceAll("/word/charts/chart", "")
                        .replaceAll("\\.xml", "")
                        .replaceAll(" - Content Type: application/vnd\\.openxmlformats-officedocument\\.drawingml\\.chart\\+xml", "")
                        .trim();
                System.out.println("key：" + key);
                chartsMap.put(key, t);
            }
        });
        //成功识别图表数量
        System.out.println("\n图表数量：" + chartsMap.size() + "\n");

        return chartsMap;
    }
}
